package org.jeecg.modules.front.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.yinsheng.YinShengClient;
import org.jeecg.modules.yinsheng.command.QueryBankListReqCommand;
import org.jeecg.modules.yinsheng.command.QueryBankListRespCommand;
import org.jeecg.modules.yinsheng.command.base.HeadResponseCommand;
import org.jeecg.modules.yinsheng.command.base.MerchantHeadRequestCommand;
import org.jeecg.modules.yinsheng.command.transfer.TransferInnerReqCommand;
import org.jeecg.modules.yinsheng.command.transfer.TransferInnerRespCommand;
import org.jeecg.modules.yinsheng.command.wallet.*;
import org.jeecg.modules.yinsheng.common.ServiceEnum;
import org.jeecg.modules.yinsheng.common.YsPayConstant;
import org.jeecg.modules.yinsheng.utils.JsonParser;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

/** Native 支付下单为例 */
@Slf4j
public class YinShengUtil {
    // 代理商编号 无需设置
    private static String agentNo;
    // 正式环境 -发起方商户号
    private static String prdSrcMerchantNo;
    // 正式环境 - 私钥密码
    private static String prdMerchantPrxPwd;
    // 正式环境 - 公钥文件 本项目中 readme 文件夹
    private static String pubKeyPath;
    // 正式环境 - 私钥文件 本项目中 readme 文件夹
    private static String prdMerchantPrx;
    // 正式环境 - 收款方银盛商户号
    private static String prdPayeeMerchantNo;
    // 正式环境 - 开放密钥
    private static String rsaPrd;
    /** 回调域名 */
    private static String notifyUrl;

    private static String wAppID;

    private static String wAppSecret;

    private static String report;


    public static void setReport(String report) {
        YinShengUtil.report = report;
    }

    public static String getReport() {
        return report;
    }


    public static void setAgentNo(String agentNo) {
        YinShengUtil.agentNo = agentNo;
    }

    public static String getAgentNo() {
        return agentNo;
    }

    public static void setPrdSrcMerchantNo(String prdSrcMerchantNo) {
        YinShengUtil.prdSrcMerchantNo = prdSrcMerchantNo;
    }

    public static String getPrdSrcMerchantNo() {
        return prdSrcMerchantNo;
    }

    public static void setPrdMerchantPrxPwd(String prdMerchantPrxPwd) {
        YinShengUtil.prdMerchantPrxPwd = prdMerchantPrxPwd;
    }

    public static String getPrdMerchantPrxPwd() {
        return prdMerchantPrxPwd;
    }

    public static void setPubKeyPath(String pubKeyPath) {
        YinShengUtil.pubKeyPath = pubKeyPath;
    }

    public static String getPubKeyPath() {
        return pubKeyPath;
    }

    public static void setPrdMerchantPrx(String prdMerchantPrx) {
        YinShengUtil.prdMerchantPrx = prdMerchantPrx;
    }

    public static String getPrdMerchantPrx() {
        return prdMerchantPrx;
    }

    public static void setPrdPayeeMerchantNo(String prdPayeeMerchantNo) {
        YinShengUtil.prdPayeeMerchantNo = prdPayeeMerchantNo;
    }

    public static String getPrdPayeeMerchantNo() {
        return prdPayeeMerchantNo;
    }

    public static void setRsaPrd(String rsaPrd) {
        YinShengUtil.rsaPrd = rsaPrd;
    }

    public static String getRsaPrd() {
        return rsaPrd;
    }

    public static void setNotifyUrl(String notifyUrl) {
        YinShengUtil.notifyUrl = notifyUrl;
    }

    public static String getNotifyUrl() {
        return notifyUrl;
    }

    public static void setWAppID(String wAppID) {
        YinShengUtil.wAppID = wAppID;
    }

    public static String getWAppID() {
        return wAppID;
    }

    public static void setWAppSecret(String wAppSecret) {
        YinShengUtil.wAppSecret = wAppSecret;
    }

    public static String getWAppSecret() {
        return wAppSecret;
    }


    public static void report(Map<String, Object> jsonObject) {
        HttpClient httpClient = HttpClients.createDefault();


        // 创建HttpPost实例，并指定URL
        HttpPost httpPost = new HttpPost(YinShengUtil.getReport());

        // 设置请求头部的Content-Type
        httpPost.setHeader("Content-Type", "application/json");

        try {
            // 创建请求内容

            // 创建ObjectMapper实例
            ObjectMapper objectMapper = new ObjectMapper();
            // 将Map转换为String
            String json = objectMapper.writeValueAsString(jsonObject);
            StringEntity requestEntity = new StringEntity(json);
            httpPost.setEntity(requestEntity);

            // 执行请求并获得响应
            HttpResponse response = httpClient.execute(httpPost);

            // 从响应中获取内容
            String responseContent = EntityUtils.toString(response.getEntity());
        } catch (Exception e) {

        }
    }


    public static Result<JSONObject> WalletRegister(String name,String certNo,String phone) {
        //先构建请求客户端
        YinShengClient sofaClient = new YinShengClient(ServiceEnum.WALLET_REGISTER, YsPayConstant.ENV_PRD, YinShengUtil.getPrdMerchantPrx(), YinShengUtil.getPrdMerchantPrxPwd(), YinShengUtil.getRsaPrd());
        MerchantHeadRequestCommand headRequestCommand = new MerchantHeadRequestCommand()
                .setSrcMerchantNo(YinShengUtil.getPrdSrcMerchantNo());
        headRequestCommand.setServiceNo("walletRegister");
        WalletRegisterReqCommand requestCommand = new WalletRegisterReqCommand();
        requestCommand.setRequestNo(OrderNum("WT"));
        requestCommand.setName(name);
        requestCommand.setCertType("01");
        requestCommand.setCertNo(certNo);
        requestCommand.setMobile(phone);
        HeadResponseCommand baseResponseCommand = sofaClient.doAction(headRequestCommand, requestCommand);
        log.info(baseResponseCommand.toString());
        // 返回
        WalletRegisterRespCommand respCommand = JsonParser
                .parserJsonStringToJavaObject(baseResponseCommand.getBizResponseJson(), WalletRegisterRespCommand.class);
        String respJson = JsonParser.parserJavaObjectToJsonString(respCommand, true);
        JSONObject jsonObject = JSON.parseObject(respJson);
        if(jsonObject.get("subCode").equals("COM000"))
        {
            return Result.ok(jsonObject);
        }
        else
        {
            return Result.error(String.valueOf(jsonObject.get("subMsg")));
        }

    }


    public static Result<JSONObject> QueryBankList(String protocolType) {
        // 先构建请求客户端
        YinShengClient yinShengClient = new YinShengClient(ServiceEnum.WALLET_REGISTER, YsPayConstant.ENV_PRD, YinShengUtil.getPrdMerchantPrx(), YinShengUtil.getPrdMerchantPrxPwd(), YinShengUtil.getRsaPrd());
        MerchantHeadRequestCommand headRequestCommand = new MerchantHeadRequestCommand()
                .setSrcMerchantNo(YinShengUtil.getPrdSrcMerchantNo());
        headRequestCommand.setServiceNo(ServiceEnum.QUERY_BANK_LIST.getApiName());
        QueryBankListReqCommand reqCommand = new QueryBankListReqCommand();
        reqCommand.setProtocolType(protocolType);
        HeadResponseCommand baseResponseCommand = yinShengClient.doAction(headRequestCommand, reqCommand);
        log.info(baseResponseCommand.toString());
        QueryBankListRespCommand respCommand = JsonParser
                .parserJsonStringToJavaObject(baseResponseCommand.getBizResponseJson(), QueryBankListRespCommand.class);
        String respJson = JsonParser.parserJavaObjectToJsonString(respCommand, false);
        JSONObject jsonObject = JSON.parseObject(respJson);
        if(jsonObject.get("subCode").equals("COM000"))
        {
            return Result.ok(jsonObject);
        }
        else
        {
            return Result.error(String.valueOf(jsonObject.get("subMsg")));
        }

    }


    /**
     * <p>钱包绑卡请求</p>
     *
     * @user linxl 2021年4月7日 下午1:02:17
     */
    public static Result<JSONObject> BindCard(String merchantno,String bankAccountNo,String bankMobile) {
        //先构建请求客户端
        YinShengClient yinShengClient = new YinShengClient(ServiceEnum.WALLET_REGISTER, YsPayConstant.ENV_PRD, YinShengUtil.getPrdMerchantPrx(), YinShengUtil.getPrdMerchantPrxPwd(), YinShengUtil.getRsaPrd());
        MerchantHeadRequestCommand headRequestCommand = new MerchantHeadRequestCommand()
                .setSrcMerchantNo(YinShengUtil.getPrdSrcMerchantNo());;
        headRequestCommand.setServiceNo("bindCard");
        BindCardReqCommand requestCommand = new BindCardReqCommand();
        requestCommand.setRequestNo(OrderNum("BC"));
        requestCommand.setMerchantNo(merchantno);
        requestCommand.setBindFunction("02");
        requestCommand.setBankAccountNo(bankAccountNo);
        requestCommand.setBankMobile(bankMobile);
        HeadResponseCommand baseResponseCommand = yinShengClient.doAction(headRequestCommand, requestCommand);
        log.info(baseResponseCommand.toString());
        // 返回
        BindCardRespCommand respCommand = JsonParser
                .parserJsonStringToJavaObject(baseResponseCommand.getBizResponseJson(), BindCardRespCommand.class);
        String respJson = JsonParser.parserJavaObjectToJsonString(respCommand, true);
        JSONObject jsonObject = JSON.parseObject(respJson);
        if(jsonObject.get("subCode").equals("COM000"))
        {
            return Result.ok(jsonObject);
        }
        else
        {
            return Result.error(String.valueOf(jsonObject.get("subMsg")));
        }


    }

    /**
     * <p>钱包解绑卡请求</p>
     *
     * @user linxl 2021年4月7日 下午1:02:17
     */
    public static Result<JSONObject>  Unbind(String merchantno,String linkId) {
        //先构建请求客户端
        YinShengClient yinShengClient = new YinShengClient(ServiceEnum.WALLET_REGISTER, YsPayConstant.ENV_PRD, YinShengUtil.getPrdMerchantPrx(), YinShengUtil.getPrdMerchantPrxPwd(), YinShengUtil.getRsaPrd());
        MerchantHeadRequestCommand headRequestCommand = new MerchantHeadRequestCommand()
                .setSrcMerchantNo(YinShengUtil.getPrdSrcMerchantNo());
        headRequestCommand.setServiceNo("unbind");
        UnBindReqCommand requestCommand = new UnBindReqCommand();
        requestCommand.setRequestNo(OrderNum("UB"));
        requestCommand.setMerchantNo(merchantno);
        requestCommand.setLinkId(linkId);
        HeadResponseCommand baseResponseCommand = yinShengClient.doAction(headRequestCommand, requestCommand);
        log.info(baseResponseCommand.toString());
        // 返回
        UnBindRespCommand respCommand = JsonParser
                .parserJsonStringToJavaObject(baseResponseCommand.getBizResponseJson(), UnBindRespCommand.class);
        String respJson = JsonParser.parserJavaObjectToJsonString(respCommand, true);
        JSONObject jsonObject = JSON.parseObject(respJson);
        if(jsonObject.get("subCode").equals("COM000"))
        {
            return Result.ok(jsonObject);
        }
        else
        {
            return Result.error(String.valueOf(jsonObject.get("subMsg")));
        }


    }


    /**
     *
     * <p>平台内转账申请</p>
     *
     * @user ljt 2022年6月16日 上午9:54:36
     */
    public static Result<JSONObject> transferInner(String merchantno,String amount,String requestNo,String transferType) {
        // 先构建请求客户端
        YinShengClient yinShengClient = new YinShengClient(ServiceEnum.WALLET_REGISTER, YsPayConstant.ENV_PRD, YinShengUtil.getPrdMerchantPrx(), YinShengUtil.getPrdMerchantPrxPwd(), YinShengUtil.getRsaPrd());
        MerchantHeadRequestCommand headRequestCommand = new MerchantHeadRequestCommand()
                .setSrcMerchantNo(YinShengUtil.getPrdSrcMerchantNo());
        String uuid = UUID.randomUUID().toString().replace("-", "");
        headRequestCommand.setServiceNo(ServiceEnum.TRANSFER_INNER.getApiName());
        TransferInnerReqCommand reqCommand = new TransferInnerReqCommand();
        reqCommand.setAmount(amount);
        reqCommand.setMerchantNo(YinShengUtil.getPrdMerchantPrx());
        reqCommand.setOrderDesc("平台内转账申请");
        reqCommand.setPayeeMerchantNo(merchantno);
        reqCommand.setPayerMerchantNo(YinShengUtil.getPrdPayeeMerchantNo());
        reqCommand.setRequestNo(requestNo);
        reqCommand.setTransferType(transferType);
        reqCommand.setNotifyUrl(YinShengUtil.getNotifyUrl()+"front/userHomeOrder/yinsheng/notify");
        HeadResponseCommand baseResponseCommand = yinShengClient.doAction(headRequestCommand, reqCommand);
        log.info(baseResponseCommand.toString());
        TransferInnerRespCommand respCommand = JsonParser
                .parserJsonStringToJavaObject(baseResponseCommand.getBizResponseJson(), TransferInnerRespCommand.class);
        String respJson = JsonParser.parserJavaObjectToJsonString(respCommand, false);
        JSONObject jsonObject = JSON.parseObject(respJson);
        if(jsonObject.get("subCode").equals("COM000")&&jsonObject.get("state").equals("SUCCESS"))
        {
            return Result.ok(jsonObject);
        }
        else
        {
            return Result.error(String.valueOf(jsonObject.get("subMsg")));
        }
    }



    /**
     * <p>钱包账户提现</p>
     *
     * @user linxl 2021年4月7日 下午1:02:17
     */
    public static Result<JSONObject> withdraw(String requestNo, String payeeMerchantNo, String amount, String linkId) {
        //先构建请求客户端
        YinShengClient yinShengClient = new YinShengClient(ServiceEnum.WALLET_REGISTER, YsPayConstant.ENV_PRD, YinShengUtil.getPrdMerchantPrx(), YinShengUtil.getPrdMerchantPrxPwd(), YinShengUtil.getRsaPrd());
        MerchantHeadRequestCommand headRequestCommand = new MerchantHeadRequestCommand()
                .setSrcMerchantNo(YinShengUtil.getPrdSrcMerchantNo());
        headRequestCommand.setServiceNo("withdraw");
        WithdrawReqCommand requestCommand = new WithdrawReqCommand();
        requestCommand.setRequestNo(requestNo);
        requestCommand.setMerchantNo(payeeMerchantNo);
        requestCommand.setAmount(amount);
        requestCommand.setLinkId(linkId);
        requestCommand.setRemark("提取");
        requestCommand.setNotifyUrl(YinShengUtil.getNotifyUrl()+"front/userHomeOrder/yinsheng/notify");
        HeadResponseCommand baseResponseCommand = yinShengClient.doAction(headRequestCommand, requestCommand);
        log.info(baseResponseCommand.toString());
        // 返回
        WithdrawRespCommand respCommand = JsonParser
                .parserJsonStringToJavaObject(baseResponseCommand.getBizResponseJson(), WithdrawRespCommand.class);
        String respJson = JsonParser.parserJavaObjectToJsonString(respCommand, true);
        JSONObject jsonObject = JSON.parseObject(respJson);
        if(jsonObject.get("subCode").equals("COM004")&&jsonObject.get("state").equals("PROCESSING"))
        {
            return Result.ok(jsonObject);
        }
        else
        {
            return Result.error(String.valueOf(jsonObject.get("subMsg")));
        }

    }


    public static Result<JSONObject>  UserInfoByCertNo(String certNo) {
        //先构建请求客户端
        YinShengClient yinShengClient = new YinShengClient(ServiceEnum.WALLET_REGISTER, YsPayConstant.ENV_PRD, YinShengUtil.getPrdMerchantPrx(), YinShengUtil.getPrdMerchantPrxPwd(), YinShengUtil.getRsaPrd());
        MerchantHeadRequestCommand headRequestCommand = new MerchantHeadRequestCommand()
                .setSrcMerchantNo(YinShengUtil.getPrdSrcMerchantNo());
        headRequestCommand.setServiceNo("userInfo");
        UserInfoReqCommand requestCommand = new UserInfoReqCommand();
        requestCommand.setCertNo(certNo);
        HeadResponseCommand baseResponseCommand = yinShengClient.doAction(headRequestCommand, requestCommand);
        log.info(baseResponseCommand.toString());
        // 返回
        UserInfoRespCommand respCommand = JsonParser
                .parserJsonStringToJavaObject(baseResponseCommand.getBizResponseJson(), UserInfoRespCommand.class);
        String respJson = JsonParser.parserJavaObjectToJsonString(respCommand, true);
        JSONObject jsonObject = JSON.parseObject(respJson);
        if(jsonObject.get("subCode").equals("COM000"))
        {
            return Result.ok(jsonObject);
        }
        else
        {
            return Result.error(String.valueOf(jsonObject.get("subMsg")));
        }

    }

    public static Result<JSONObject>  UserInfoByMerchantno(String merchantNo) {
        //先构建请求客户端
        YinShengClient yinShengClient = new YinShengClient(ServiceEnum.WALLET_REGISTER, YsPayConstant.ENV_PRD, YinShengUtil.getPrdMerchantPrx(), YinShengUtil.getPrdMerchantPrxPwd(), YinShengUtil.getRsaPrd());
        MerchantHeadRequestCommand headRequestCommand = new MerchantHeadRequestCommand()
                .setSrcMerchantNo(YinShengUtil.getPrdSrcMerchantNo());
        headRequestCommand.setServiceNo("userInfo");
        UserInfoReqCommand requestCommand = new UserInfoReqCommand();
        requestCommand.setMerchantNo(merchantNo);
        HeadResponseCommand baseResponseCommand = yinShengClient.doAction(headRequestCommand, requestCommand);
        log.info(baseResponseCommand.toString());
        // 返回
        UserInfoRespCommand respCommand = JsonParser
                .parserJsonStringToJavaObject(baseResponseCommand.getBizResponseJson(), UserInfoRespCommand.class);
        String respJson = JsonParser.parserJavaObjectToJsonString(respCommand, true);
        JSONObject jsonObject = JSON.parseObject(respJson);
        if(jsonObject.get("subCode").equals("COM000"))
        {
            return Result.ok(jsonObject);
        }
        else
        {
            return Result.error(String.valueOf(jsonObject.get("subMsg")));
        }

    }


    public static String OrderNum(String prefix)
    {
        // 格式化输出日期和时间，包括分和秒
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String formattedDateTime = now.format(formatter);
        Random random = new Random();
        int randomNumber = random.nextInt(9000) + 1000;
        return prefix+formattedDateTime+String.valueOf(randomNumber);
    }



}
